package com.tuo51.evaluate.service.impl;

import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.repository.ChildrenRepository;
import com.tuo51.evaluate.service.EvaluateUploadService;
import com.tuo51.evaluate.service.EvaluateV2ExportService;
import com.tuo51.foudation.utils.DateUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.transaction.Transactional;
import java.io.*;
import java.nio.file.Files;
import java.util.Objects;

import static com.matt.foundation.model.ErrorCode.CHILDREN_NOT_EXIST;
import static com.matt.foundation.model.ErrorCode.STAFF_NOT_EXIST;

/**
 * *******************************
 * Created by Ron.
 * form com.tuo51
 * on 2017/7/26
 * *******************************
 */
@Service
@Transactional
public class EvaluateUploadServiceImpl implements EvaluateUploadService {

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private OSSProcessService fileProcessService;

//    @Autowired
//    private EvaluateStaffService evaluateStaffService;

    @Value("${aliyun.oss.filePathPrefix}")
    private String filePathPrefix;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

    public final static String VIDEO_PARENT = "daily_record_video";
    public final static String PHOTO_PARENT = "daily_record_photo";
    public final static String FILE_OP_STAFF = "file_op_staff";


    @Override
    public Children uploadChildrenHeadImg(String childrenId, MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children))
            throw new BusinessException(CHILDREN_NOT_EXIST, "宝宝不存在");
        String fileName = children.getId() + "/" + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + "children/" + fileName, file);
        children.setImgUrl(IMG_SERVICE_PREFIX + relativePath);
        childrenRepository.save(children);
        return children;
    }

//    @Override
//    public String uploadTeacherHeadImg(String staffId, MultipartFile file) {
//        String extension = getExtension(file);
//
//        if (Objects.isNull(staffId))
//            throw new BusinessException(STAFF_NOT_EXIST, "老师不存在");
//
//        String fileName = staffId + "/" + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
//        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + "teacher/" + fileName, file);
//        String url = IMG_SERVICE_PREFIX + relativePath;
//
//        evaluateStaffService.modifyHeadImg(staffId, url);
//
//        return url;
//    }
//
//    @Override
//    public String uploadAreaLogo(String staffId, MultipartFile file){
//        String extension = getExtension(file);
//
//        String fileName = staffId + "/" + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
//        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + "area/" + fileName, file);
//        String url = IMG_SERVICE_PREFIX + relativePath;
//
//        evaluateStaffService.modifyHeadImg(staffId, url);
//
//        return url;
//    }

    private static String getExtension(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        return extension;
    }


    @Override
    public String uploadObservationRecordImg(Integer type, MultipartFile[] files) {
        return uploadMultiPartFiles(type, "observation_record", null, files);
    }

    @Override
    public String uploadStaticPhotoAlbum(String filePath) throws IOException {
        return uploadLocalFile(filePath, EvaluateV2ExportService.ExportType.H5, "时光相册");
    }

    @Override
    public String uploadLocalFile(String localFileURL, EvaluateV2ExportService.ExportType type, String prefix){
        try {
            return uploadLocalFileE(localFileURL, type, prefix);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String uploadLocalFileE(String localFileURL, EvaluateV2ExportService.ExportType type, String fileNamePrefix) throws IOException {
        File file = new File(localFileURL);
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());

        String uploadedResult = null;
        //写文件
        try {
            InputStream input = new FileInputStream(file);
            OutputStream os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            // Or faster..
            // IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());

            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

//            String fileName = fileNamePrefix + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
//            String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM") + "/" + fileName, file);
//            https://e.res.tuo51.com/51evaluation/file/evaluate_report/2020-08/%E7%8E%8B%E7%BB%98%E7%84%B6_%E5%BF%83%E7%90%86%E8%A1%8C%E4%B8%BA%E8%AF%84%E6%B5%8B%E6%8A%A5%E5%91%8A_2020-08-15_10-34-29-322.doc
//            filePathPrefix: 51evaluation_dev/file/

            String fileName = filePathPrefix + type.getFolderName() + "/" + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM") + "/";
            String timestamp = DateUtil.millisToDateTime(System.currentTimeMillis(), "dd_HH-mm-ss-SSS");
            fileName += String.format(type.getFileName(), fileNamePrefix, timestamp);

            uploadedResult = uploadFile(fileName, multipartFile);

        } catch (IOException ex) {
            // do something.
            ex.printStackTrace();
        } finally {
            if(file.exists()){
                file.delete();
            }
        }

        return uploadedResult;
    }

    public String uploadMultiPartFiles(Integer type, String secondPath, String staffId, MultipartFile[] files) {
        String fileName = "";
        if (2 == type) {
            String originalName = files[0].getOriginalFilename();
            String extension = originalName.substring(originalName.lastIndexOf("."));
            fileName += DateUtil.millisToDateTime(System.currentTimeMillis(), "_yyyy-MM-dd_HH-mm-ss-SSS") + extension;
            String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + "/video/" + fileName, files[0]);
            return IMG_SERVICE_PREFIX + relativePath;
        } else if (1 == type) {
            String filePath = "";
            for (MultipartFile file : files) {
                fileName = "";
                String originalName = file.getOriginalFilename();
                String extension = originalName.substring(originalName.lastIndexOf("."));
                fileName += DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
                String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + "/img/" + fileName, file);
                filePath += IMG_SERVICE_PREFIX + relativePath + "|";
            }
            return StringUtils.substring(filePath, 0, filePath.length() - 1);
        }
        return null;
    }

    @Override
    public String uploadParentPhotos(String staffId, MultipartFile[] files) {
        if (Objects.isNull(staffId))
            throw new BusinessException(STAFF_NOT_EXIST, "用户信息不存在");

        String [] ret = new String[files.length];
        for (int i = 0; i < files.length; i++){
            MultipartFile file = files[i];
            ret[i] = uploadStaffFile(staffId, PHOTO_PARENT, file);
        }
        return StringUtils.join(ret, "|");
    }

    @Override
    public String uploadParentVideos(String staffId, MultipartFile[] files) {
        if (Objects.isNull(staffId))
            throw new BusinessException(STAFF_NOT_EXIST, "用户信息不存在");

        String [] ret = new String[files.length];
        for (int i = 0; i < files.length; i++){
            MultipartFile file = files[i];
            ret[i] = uploadStaffFile(staffId, VIDEO_PARENT, file);
        }
        return StringUtils.join(ret, "|");
    }

    @Override
    public String uploadStaffFile(String staffId, String folder, MultipartFile file) {
        String extension = getExtension(file);

        String fileName = DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;

        String relativePath = filePathPrefix + folder + "/" + staffId + "/" + fileName;

        String url = uploadFile(relativePath, file);

        return url;
    }

    private String uploadFile(String fileName, MultipartFile file) {
        String relativePath = fileProcessService.aliyunOssUpload(fileName, file);
        return IMG_SERVICE_PREFIX + relativePath;
    }
}
